package com.chat.net;

import com.chat.entity.DataPackage;
import com.chat.server.BaseServerManager;
import com.chat.server.ServerManager;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.util.LinkedList;


/**
 * object客户端处理器
 */
public class ChatObjectServerHandler extends ChannelInboundHandlerAdapter {

    //发送集合
    private LinkedList<DataPackage> sender;
    //接收集合
    private LinkedList<DataPackage> reader;
    ServerManager serverManager;


    public ChatObjectServerHandler() {
        sender = new LinkedList();
        reader = new LinkedList();
        serverManager = new BaseServerManager();
    }

    //push sender
    public synchronized void addObject(Object o){
        if(o instanceof DataPackage)
            sender.push((DataPackage)o);
    }

    //pop reader
    public synchronized Object getObject(){
        if(!reader.isEmpty())
            return reader.pop();
        return new NullPointerException("没有新的消息哦");
    }

    @Override
    public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
        super.channelRegistered(ctx);
    }

    /**
     * 读取管道数据
     * @param ctx
     * @param msg
     * @throws Exception
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        if(msg instanceof DataPackage) {

            DataPackage sourceDataPackage = (DataPackage) msg;
            reader.push(sourceDataPackage);//push reader

            DataPackage result = serverManager.allocateObject(sourceDataPackage);
            ctx.writeAndFlush(result);
        }
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        if(!sender.isEmpty())
            ctx.writeAndFlush(sender.pop());//pop sender
    }



    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }

}
